using System.Collections.Generic;
using System.Linq;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace DevelopmentKit.Extensions.SharpArch.NHibernateMaps.Conventions
{
    public class HasManyToManyConvention : IHasManyToManyConvention
    {
        public void Apply(IManyToManyCollectionInstance instance)
        {
            var prefix = System.Configuration.ConfigurationManager.AppSettings["nhibernate.mapping.prefix"];
            var entitys = new List<string>();
            var entityDatabaseName = instance.EntityType.Name;
            var childDatabaseName = instance.ChildType.Name; 
            entitys.Add(entityDatabaseName);
            entitys.Add(childDatabaseName);
            instance.Table(prefix + entitys.OrderBy(x => x).First() + "_" + entitys.OrderBy(x => x).Last());
            instance.Key.Column(entityDatabaseName + "Id");
            instance.Relationship.Column(childDatabaseName + "Id");
        }
    }
}